package com.sh.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtTokenUtil {

    private static String key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    private static final long EXPIRATION = 1000 * 30 * 60 * 1000  ;

    public String encodeJwt(Map payloadMap){
        // header部分
        Map headerMap = new HashMap();
        headerMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headerMap.put("typ", "JWT");
        Date eDate = new Date(System.currentTimeMillis() + EXPIRATION);
        payloadMap.put("expiration", eDate);
        // 生成token
        String jwtToken = Jwts.builder()
                .setHeaderParams(headerMap)
                .setClaims(payloadMap)
                .setSubject("user")   //  token所面向的用户
                .setIssuedAt(new Date())   //  token的签发时间
                .setExpiration(eDate)     //  token过期时间
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
        return jwtToken;
    }

    public String encodeJwt(String key, Map payloadMap){
        // header部分
        Map headerMap = new HashMap();
        headerMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headerMap.put("typ", "JWT");

        // 生成token
        String jwtToken = Jwts.builder()
                .setHeaderParams(headerMap)
                .setClaims(payloadMap)
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
        return jwtToken;
    }

    public Claims decodeJWTWithKey(String jwtToken, String key){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwtToken).getBody();
            return claims;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("JWT解析异常");
        }
        return null;
    }


    public Claims decodeJWTWithKey(String token){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        }catch (Exception e){
            e.printStackTrace();
            log.error("令牌过期");
        }
        return null;
    }

    public boolean isTokenExpired(String jwtToken) {
        if ( jwtToken==null || jwtToken.isEmpty() ){
            log.error("jwtToken is null");
            return true;
        }
        try {
            Date time = new Date( Long.parseLong(decodeJWTWithKey(jwtToken).get("expiration").toString()) );
            return time.before(new Date());
        } catch (Exception e) {
           log.error("jwtToken 时间可能有问题");
           return false;
        }
    }

}
